from models import SirogiUser
from django.shortcuts import render_to_response, get_object_or_404
import copy
from django.contrib.auth.decorators import login_required
from sirogi.documents.models import Document
from django.template import RequestContext

@login_required
def index(request):

    search = False
    
    if request.POST.has_key('search_login'):
        username = request.POST['search_login']
        search = True
    else:
        username = None

    if request.POST.has_key('search_last_name'):
        last_name = request.POST['search_last_name']
        search = True
    else:
        last_name = None

    if search:
        all_results = list(SirogiUser.objects.all())
        results = []

        for i in all_results:
            if username and username not in i.username:
                continue

            if last_name and last_name not in i.last_name:
                continue

            results.append(i)

    else:
        results = None

    try:
        is_manager = request.user.is_SirogiManager()
    except:
        is_manager = False
    
    return render_to_response('users/index.html', {'results': results, 'is_manager':is_manager}, RequestContext(request))

@login_required
def detail(request, username):
    user = get_object_or_404(SirogiUser, username=username)

    try:
        documents = Document.objects.filter(owner=user)
    except Document.DoesNotExist:    
        documents = False
    
    return render_to_response('users/detail.html', {'local_user': user, 'documents':documents}, RequestContext(request))
    
